package com.muqi.app.qlearn.publish;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.easemob.easeui.widget.CircularImage;
import com.muqi.app.network.http.GlideImageUtils;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.ShareDialog;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.project.utils.TimeMangerUtil;
import com.muqi.app.qlearn.adapter.CommentAdapter;
import com.muqi.app.qlearn.adapter.HomeWkPhotoAdapter;
import com.muqi.app.qlearn.adapter.LikeHeadAdapter;
import com.muqi.app.qlearn.modles.CommentBean;
import com.muqi.app.qlearn.modles.MediaInfo;
import com.muqi.app.qlearn.modles.PersonBean;
import com.muqi.app.qlearn.modles.RecordDetailBean;
import com.muqi.app.qlearn.modles.RecordFile;
import com.muqi.app.qlearn.student.BaseSpeechActivity;
import com.muqi.app.qlearn.student.MenuActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.ui.JuBaoActivity;
import com.muqi.app.qlearn.ui.UserHomepagerActivity;

import com.muqi.app.user.widget.MyGridView;
import com.muqi.app.user.widget.RecordDetialWindow;
import com.muqi.app.user.widget.RecordDetialWindow.RecordDetialWindowListener;
import com.muqi.app.user.widget.RecordTextEntry;
import com.muqi.app.user.widget.WxPraiseWindow;
import com.muqi.app.utils.ChineseUtils;
import com.muqi.app.widget.pulltorefresh.XListView;
import com.muqi.app.widget.scanpicture.ScanPictureActivity;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog.OnSweetClickListener;

public class RecordDetailActivity extends BaseSpeechActivity implements
		XListView.IXListViewListener, OnItemClickListener, OnClickListener,
		WxPraiseWindow.ClickWxListener, RecordDetialWindowListener {
	public static final String RECORD_ID = "record_id";
	private XListView mListview;
	private EditText contentEdt;
	private CircularImage mAvatar;
	private TextView mName;
	private TextView mContent;
	private MyGridView itemPicView;
	private TextView recordName;
	private TextView recordTime;
	private LinearLayout contentLayout;
	private ImageButton priseButton;
	private RecordDetailBean getDetail = null;
	private HomeWkPhotoAdapter photoAdapter = null;
	private List<MediaInfo> photoLists = new ArrayList<MediaInfo>();

	private List<CommentBean> commentlist = new ArrayList<CommentBean>();
	private CommentAdapter mAdapter = null;
	private int page = 1;
	private String recordId = "";
	private String reply_user_id = "";
	private WxPraiseWindow wxWindow = null;
	private boolean hasPraised = false;

	private RecordDetialWindow rdWindow;
	private ShareDialog dialog;
	private String shareTitle = "成长记录";
	private ImageView iv_more;

	private MyGridView gv_like;
	private LikeHeadAdapter headAdapter;
	private ArrayList<PersonBean> beans;
	private boolean isParent;
	private TextView recordAddress;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		recordId = getIntent().getStringExtra(RECORD_ID);
		if (recordId == null || TextUtils.isEmpty(recordId)) {
			finish();
		}
		setContentView(R.layout.aty_homework_details);
	}

	@SuppressLint("InflateParams")
	@Override
	protected void onInit() {
		TextView mTitle = (TextView) findViewById(R.id.detail_title);
		mTitle.setText("成长记录");
		mListview = (XListView) findViewById(R.id.xListView);
		mListview.setXListViewListener(this);
		mListview.setPullLoadEnable(false);
		mListview.setPullRefreshEnable(false);
		mListview.setOnItemClickListener(this);
		contentEdt = (EditText) findViewById(R.id.contentEditText);

		View headerView = LayoutInflater.from(this).inflate(
				R.layout.header_record_detail, null);

		mAvatar = (CircularImage) headerView.findViewById(R.id.record_avatar);
		mName = (TextView) headerView.findViewById(R.id.record_name);
		mContent = (TextView) headerView.findViewById(R.id.record_content);
		itemPicView = (MyGridView) headerView.findViewById(R.id.myGridView);
		recordName = (TextView) headerView.findViewById(R.id.record_type_name);
		recordTime = (TextView) headerView.findViewById(R.id.record_time);
		recordAddress=(TextView) headerView.findViewById(R.id.address);
		contentLayout = (LinearLayout) headerView
				.findViewById(R.id.contentLayout);
		priseButton = (ImageButton) headerView.findViewById(R.id.record_button);
		priseButton.setOnClickListener(this);

		mListview.addHeaderView(headerView);
		mListview.setAdapter(null);
		iv_more = (ImageView) findViewById(R.id.iv_more);
		iv_more.setVisibility(View.VISIBLE);
		iv_more.setOnClickListener(this);
		rdWindow = new RecordDetialWindow(this, this);
		gv_like = (MyGridView) headerView.findViewById(R.id.myGridView_like);
		dialog = new ShareDialog(this, shareTitle, MContants.SHARE_URL);
	}

	@Override
	protected void onData() {
		super.onData();
		showLoading();
		if (mSpUtil.getUserType().equals(MContants.LOGIN_AS_PARENTS)) {
			isParent = true;
		} else {
			isParent = false;
		}
		loadingRecordDetails();
		loadingDetailComments();
		loadingLike();
	}

	/**
	 * 获得点赞的数据
	 */
	private void loadingLike() {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("id", recordId);// 'class_job','goods','socially_activity','message'
		String requestUrl = ParamsUtils.buildParams(NetWorkApi.LIKE_LIST_API,
				sendMap);
		MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				Log.e("===", result);
				if (resuleCode == RESULTCODE.SUCCESS) {
					beans = ResponseUtils.getLikeList(
							RecordDetailActivity.this, result);
					Log.e("===", beans + " beans");
					if (beans != null) {
						headAdapter = new LikeHeadAdapter(
								RecordDetailActivity.this, beans);
						gv_like.setAdapter(headAdapter);
					}

				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.record_button:
			if (wxWindow == null) {
				wxWindow = new WxPraiseWindow(this, this);
			}
			wxWindow.showPopupWindow(v, hasPraised);
			break;
		case R.id.iv_more:
			if (getDetail != null) {
				if (rdWindow == null) {
					rdWindow = new RecordDetialWindow(this, this);
				}
				rdWindow.showPopupWindow(iv_more);
			}

			break;
		default:
			break;
		}
	}

	private void loadingRecordDetails() {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("id", recordId);
			sendMap.put("token", mSpUtil.getToken());
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.MY_RECORD_DETAIL_API, sendMap);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					getDetail = ResponseUtils
							.getRecordDetails(mContext, result);
					if (getDetail != null) {
						showRecordDetailView();
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	protected void showRecordDetailView() {
		Log.e("===", getDetail.clickLike);
		if("yes".equals(getDetail.clickLike)){
			hasPraised=true;
		}else{
			hasPraised=false;
		}
		if (getDetail.studentInfo != null) { // 代表查看的是学生的成长记录
			GlideImageUtils.setAvatar(this,
					getDetail.studentInfo.avatarInfo.fileurl_02, mAvatar);
			mName.setText(getDetail.studentInfo.name);
			rdWindow.isShowZhuanZai(false, false); // 老师发布的并且是自己的可以转载到自己的孩子的成长树上
			if (getDetail.studentInfo.id.equals(mSpUtil.getCurrentChildId())) {
				if ("1".equals(getDetail.tag)) {
					rdWindow.isOwn(true, true); // 转载的不能申请加积分
				} else {
					rdWindow.isOwn(true, false); // 非转载的申请加积分
				}

			} else {
				rdWindow.isOwn(false, false);

			}
			// 点击该学生进行关注或取消关注
			mAvatar.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent();
					intent.putExtra(UserHomepagerActivity.IM_OR_MOBILE_OR_USERID,getDetail.studentInfo.im_user_id);
					intent.setClass(RecordDetailActivity.this, UserHomepagerActivity.class);
					startActivity(intent);
				}
			});
		} else {
			rdWindow.isShowZhuanZai(true, true); // 老师发布的并且是自己的可以转载到自己的孩子的成长树上
			/*if(getDetail.student_id.equals(mSpUtil.getCurrentChildId())){
				
			}else{
				rdWindow.isShowZhuanZai(isParent, false);
			}*/
			rdWindow.isOwn(false, false);
			mName.setText(getDetail.classname);
			mAvatar.setImageResource(R.drawable.tree_class_default);
		}

		dialog.setTitle(getDetail.content);
		mContent.setText(getDetail.content);
		recordName.setText(ChineseUtils.getSquality(getDetail.fname,
				getDetail.sname));
		recordTime.setText(TimeMangerUtil
				.getChinesetimeView(getDetail.create_time));

		if (getDetail.tkey != null && getDetail.tvalue != null) {
			if (getDetail.tkey.length == getDetail.tvalue.length) {
				for (int i = 0; i < getDetail.tvalue.length; i++) {
					RecordTextEntry mTextView = new RecordTextEntry(this,
							getDetail.tkey[i], getDetail.tvalue[i]);
					if (mTextView != null) {
						contentLayout.addView(mTextView);
					}
				}
			}
		}

		if (getDetail.pics != null && getDetail.pics.size() > 0) {
			for (RecordFile file : getDetail.pics) {
				photoLists.add(file.pic);
			}
			photoAdapter = new HomeWkPhotoAdapter(this, photoLists);
			itemPicView.setAdapter(photoAdapter);
			itemPicView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					List<String> bigUrls = new ArrayList<String>();
					for (MediaInfo info : photoLists) {
						bigUrls.add(info.fileurl_03);
					}
					if (bigUrls.size() > 0) {
						Intent intent = new Intent(RecordDetailActivity.this,
								ScanPictureActivity.class);
						intent.putExtra(ScanPictureActivity.EXTRA_IMAGE_URLS,
								(ArrayList<String>) bigUrls);
						intent.putExtra(ScanPictureActivity.EXTRA_IMAGE_INDEX,
								arg2);
						startActivity(intent);
					}
				}
			});
		}
		if (getDetail.address != null && !getDetail.address.equals("")) {
			recordAddress.setText(getDetail.address);
		}
	}

	/**
	 * 关注该学生
	 */
	private void followPerson(String id) {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("id", id);
		sendMap.put("action", "yes");
		sendMap.put("token", mSpUtil.getToken());
		String requestUrl = ParamsUtils.buildParams(
				NetWorkApi.MY_CONCERN_ACTION_API, sendMap);
		MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				if (resuleCode == RESULTCODE.SUCCESS) {
					showToast("关注成功");
				}
			}
		});

	}

	private void loadingDetailComments() {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("id", recordId);
			sendMap.put("type", "grow_tree");// 'class_job','goods','socially_activity','message'
			sendMap.put("page", page);
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_HOMEWORK_COMMENTLISTS_API, sendMap);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					onLoadView();
					hideLoading();
					if (resuleCode == RESULTCODE.SUCCESS) {
						List<CommentBean> getLists = ResponseUtils
								.getUserComments(mContext, result);
						if (getLists != null && getLists.size() > 0) {

							if (page == 1) {
								commentlist.clear();
								commentlist = getLists;
								if (mAdapter != null)
									mAdapter = null;
								mAdapter = new CommentAdapter(mContext,
										commentlist);
								mListview.setAdapter(mAdapter);
							} else {
								for (CommentBean item : getLists) {
									commentlist.add(item);
								}
								mAdapter.notifyDataSetChanged();
							}
							if (getLists.size() < 10) {
								mListview.setPullLoadEnable(false);
							} else {
								mListview.setPullLoadEnable(true);
								page++;
							}
						}
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	private void onLoadView() {
		mListview.stopRefresh();
		mListview.stopLoadMore();
		mListview.setRefreshTime("刚刚");
	}

	public void openVoice2Words(View v) {
		startSpeech();
	}

	@Override
	protected void onSpeech2Words(String speechWords) {
		contentEdt.setText(speechWords);
		contentEdt.setSelection(contentEdt.length());
	}

	public void sendMyCreditMsg(View v) {
		String mContent = contentEdt.getText().toString();
		if (TextUtils.isEmpty(mContent)) {
			showToast("评论内容不能为空哦");
		} else {
			publiMyCommentInfo(reply_user_id, mContent);
			contentEdt.setText("");
			contentEdt.setHint("评论...");
			reply_user_id = "";
			dismissSoftKeyboard();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		if (commentlist.get(position - 2).author_userInfo.id.equals(mSpUtil
				.getUserId())) {
			return;
		}
		reply_user_id = commentlist.get(position - 2).author_userInfo.id;
		contentEdt.setHint("回复:"
				+ commentlist.get(position - 2).author_userInfo.name);
		getSoftInput(contentEdt);
	}

	private void publiMyCommentInfo(String replyUser, String content) {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("token", mSpUtil.getToken());
			sendMap.put("obj_type", "grow_tree");
			sendMap.put("obj_id", recordId);
			sendMap.put("reply_to_user_id", replyUser);
			sendMap.put("rating", 5);
			sendMap.put("content", content);
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.ADD_MYCOMMENT_TO_USER_API, sendMap);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					if (resuleCode == RESULTCODE.SUCCESS) {
						onRefresh();
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	private void publiMyPraise(String action) {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("token", mSpUtil.getToken());
			sendMap.put("id", recordId);
			sendMap.put("action", action);
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.PRAISE_TO_USER_API, sendMap);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {

					if (resuleCode == RESULTCODE.SUCCESS) {
						loadingLike();
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	@Override
	public void onRefresh() {
		page = 1;
		loadingDetailComments();
	}

	@Override
	public void onLoadMore() {
		loadingDetailComments();
	}

	public void onBack(View v) {
		this.finish();
	}

	@Override
	public void onWxClick(int wxtype) {
		if (wxtype == 1) {
			if (hasPraised) {
				publiMyPraise("no");
			} else {
				publiMyPraise("yes");
			}
			hasPraised = !hasPraised;
		} else {
			reply_user_id = "";
			contentEdt.setHint("评论...");
			getSoftInput(contentEdt);
		}
	}

	@Override
	public void onClickRecordDetialWindowListener(int id) {
		switch (id) {
		case R.id.pop_button_01: // 分享
			dialog.showShareDialog();
			break;
		case R.id.pop_button_02:// 举报
			if(getDetail!=null){
				if(!ChineseUtils.isOk(getDetail.report_status)){
					Intent intent = new Intent(RecordDetailActivity.this,
							JuBaoActivity.class);
					intent.putExtra("recordId", recordId);
					startActivityForResult(intent,10010);
				}else{
					showToast("您已经举报过了");
				}
			}
			break;
		case R.id.pop_button_03:// 积分
			new SweetAlertDialog(mContext, SweetAlertDialog.NORMAL_TYPE)
					.setTitleText("公示期本校本年级的的所有人都可以到该材料").setConfirmText("确定")
					.setConfirmClickListener(new OnSweetClickListener() {

						@Override
						public void onClick(SweetAlertDialog sweetAlertDialog) {
							sweetAlertDialog.dismiss();
							applayAdd();

						}
					}).setCancelText("取消")
					.setCancelClickListener(new OnSweetClickListener() {

						@Override
						public void onClick(SweetAlertDialog sweetAlertDialog) {
							sweetAlertDialog.dismiss();

						}
					}).show();

			break;
		case R.id.pop_button_05:// 删除
			new SweetAlertDialog(mContext, SweetAlertDialog.NORMAL_TYPE)
					.setTitleText("确定删除该记录?").setConfirmText("确定")
					.setConfirmClickListener(new OnSweetClickListener() {

						@Override
						public void onClick(SweetAlertDialog sweetAlertDialog) {
							sweetAlertDialog.dismiss();
							deleteOwn();
						}
					}).setCancelText("取消")
					.setCancelClickListener(new OnSweetClickListener() {
						@Override
						public void onClick(SweetAlertDialog sweetAlertDialog) {
							sweetAlertDialog.dismiss();

						}
					}).show();

			break;
		case R.id.pop_button_04:// 转载到成长树上
			new SweetAlertDialog(mContext, SweetAlertDialog.NORMAL_TYPE)
					.setTitleText("是否转载到成长树上?").setConfirmText("确定")
					.setConfirmClickListener(new OnSweetClickListener() {

						@Override
						public void onClick(SweetAlertDialog sweetAlertDialog) {
							sweetAlertDialog.dismiss();
							zhuanzaiTree();
						}
					}).setCancelText("取消")
					.setCancelClickListener(new OnSweetClickListener() {
						@Override
						public void onClick(SweetAlertDialog sweetAlertDialog) {
							sweetAlertDialog.dismiss();

						}
					}).show();

			break;

		default:
			break;
		}

	}

	/**
	 * 转载到成长树上
	 */

	protected void zhuanzaiTree() {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("id", recordId);
		sendMap.put("student_id", mSpUtil.getCurrentChildId());

		String requestUrl = ParamsUtils.buildParams(NetWorkApi.ZHUANZAI_API,
				sendMap);
		MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				Log.e("===", result);
				if (resuleCode == RESULTCODE.SUCCESS) {
					Toast.makeText(RecordDetailActivity.this, "转载成功",
							Toast.LENGTH_SHORT).show();

				}
			}
		});

	}

	/**
	 * 删除自己的记录
	 */
	private void deleteOwn() {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("id", recordId);
		sendMap.put("class_manager_id", mSpUtil.getChildClassId());
		String requestUrl = ParamsUtils.buildParams(NetWorkApi.DELET_RECORD,
				sendMap);
		MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				Log.e("===", result);
				if (resuleCode == RESULTCODE.SUCCESS) {
					Toast.makeText(RecordDetailActivity.this, "删除成功",
							Toast.LENGTH_SHORT).show();
					Intent broadIntent = new Intent();
					broadIntent.setAction(MContants.REFRESH_FILETREE_ACTION);
					sendBroadcast(broadIntent);

					Intent intent = new Intent(RecordDetailActivity.this,
							MenuActivity.class);
					intent.putExtra("isFree", true);
					startActivity(intent);
					finish();

				}
			}
		});

	}

	/**
	 * 申请公示加分
	 */
	protected void applayAdd() {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("id", recordId);
		String requestUrl = ParamsUtils.buildParams(
				NetWorkApi.APPLAY_ADD_INTEGERAL, sendMap);
		MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				if (resuleCode == RESULTCODE.SUCCESS) {
					Toast.makeText(RecordDetailActivity.this, "申请成功",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if(arg0==10010 && arg1==RESULT_OK){
			getDetail.report_status="y";
		}
	}
}
